
var _ = require('lodash'),
    Q = require("q"),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    qcRecordController = require('../../../QC/server/controllers/QCRecord.server.controller'),
    extendEnumController = require('../../../Common/server/controllers/ExtendEnum.server.controller'),
    completePlanController = require('../../../ProduceWork/server/controllers/CompletePlan.server.controllers'),
    enumController = require('../../../QC/server/controllers/Enum.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller');


//获取完工计划
exports.getCompletePlanByDate = function(req, res) {
    var completeDate = req.body.CompleteDate;
    console.log(completeDate);
    var resultData = []
    completePlanController.getCompletePlanByDate(completeDate, function(err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '完工计划查询失败';
                newErr.message = '未找到对应的完工计划！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                for (var i = 0; i < result.length; i++) {
                    var completeQty = 0;
                    var r = result[i];
                    if (r.CompleteQty) {
                        completeQty = r.CompleteQty;
                    } else {
                        completeQty = 0;
                    }
                    resultData.push({
                        _id: r._id,
                        Code: r.Code,
                        LotNumber: r.LotNumber,
                        Qty: r.Qty,
                        CompleteQty: completeQty,
                        QtyRate: completeQty / r.Qty * 100,
                        CompleteTime: r.CompleteTime,
                        ItemMasterCode: r.ItemMaster.Code,
                        Remark: r.Remark,
                    });
                }
                res.json({
                    Data: resultData,
                    Error: null
                });
            }
        }
    });
};

//查询流水良率
exports.queryBizRecordRate = function(req, res) {
    var b = req.body,
        date = b.date,
        workLocation = b.workLocation;
    var badTypeOptions = [];
    //查找所有的不良类型
    enumController.findAllExtendEnum("BadType", function (err, result) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        }
        else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询不良类型失败';
                newErr.message = '未找到所有的不良类型！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            }
            else {
                badTypeOptions = result.Options;
                bizRecordController.queryByDateAndWorkLocation(date, workLocation, function(err, bizRecords) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                        return;
                    }
                    if (bizRecords == null || bizRecords.length === 0) {
                        var newErr = new Error();
                        newErr.leval = 9;
                        newErr.title = '查询流水记录失败';
                        newErr.message = '未找到对应的流水记录！';
                        res.json({
                            Data: null,
                            Error: newErr
                        });
                        return;
                    } else {
                        //找到不同的ItemMasterCode
                        var ItemMasterCodes = [bizRecords[0].BarcodeMaster.ItemMasterCode];
                        for (var i = 0; i < bizRecords.length; i++) {
                            var repeat = false;
                            for (var j = 0; j < ItemMasterCodes.length; j++) {
                                if (bizRecords[i].BarcodeMaster.ItemMasterCode === ItemMasterCodes[j]) {
                                    repeat = true;
                                    break;
                                }
                            }
                            if (!repeat) {
                                ItemMasterCodes.push(bizRecords[i].BarcodeMaster.ItemMasterCode);
                            }
                        }
                        //按型号分组
                        var items = [];
                        var allNum = 0;
                        var allQualifiedNum = 0;
                        for (var i = 0; i < ItemMasterCodes.length; i++) {
                            var num = 0; //统计每型号的总数
                            var qualifiedNum = 0; //统计每型号的合格数
                            var nobizRecords = [];//统计每型号的不合格品的流水
                            for (var a = 0; a < bizRecords.length; a++) {
                                var tempCode = bizRecords[a].BarcodeMaster.ItemMasterCode;
                                if (ItemMasterCodes[i] === tempCode) {
                                    num++;
                                    if (bizRecords[a].QCStatus === 0) {
                                        qualifiedNum++;
                                    }
                                    else{
                                        nobizRecords.push(bizRecords[a]);
                                    }
                                }
                            }
                            if (num != 0) {
                                items.push({
                                    ItemMasterCode: ItemMasterCodes[i],
                                    Num: num,
                                    QualifiedNum: qualifiedNum,
                                    Rate: qualifiedNum / num * 100,
                                    nobizRecords: nobizRecords,
                                    BadTypes: []
                                });
                                allNum += num;
                                allQualifiedNum += qualifiedNum;
                            }
                        }

                        if(items.length>0){
                           //通过每个型号的不合格品的流水记录，查找品质记录，再查找不良类型，统计不良类型的种类和数量！
                            var promises = [];   
                            items.forEach(function (item) {
                                promises.push(queryEachQCRecord(item,badTypeOptions));   
                            });
                            
                            Q.all(promises).then(function () {
                                //通过每个型号的BadType数据，统计所有的BadType数据
                                var tempItems = [];
                                //去除没有BadType数据的
                                for (var i = 0; i < items.length; i++) {
                                    if(items[i].BadTypes.length>0){
                                        tempItems.push(items[i]);
                                    }   
                                }
                                //有数据
                                if(tempItems.length>0){
                                    //找到不同的BadName
                                    var allBadNames = [tempItems[0].BadTypes[0].BadTypeName];
                                    for (var i = 0; i < tempItems.length; i++) {
                                        for (var b = 0; b < tempItems[i].BadTypes.length; b++) {
                                            var repeat = false;
                                            for (var j = 0; j < allBadNames.length; j++) {
                                                if (tempItems[i].BadTypes[b].BadTypeName === allBadNames[j]) {
                                                    repeat = true;
                                                    break;
                                                }
                                            }
                                            if (!repeat) {
                                                allBadNames.push(tempItems[i].BadTypes[b].BadTypeName);
                                            }
                                        }  
                                    }

                                    //按BadName分组
                                    var itemallBadNames = [];
                                    for (var i = 0; i < allBadNames.length; i++) {   
                                        var numBadName = 0;//统计每BadName的总数  
                                        for (var a = 0; a < tempItems.length; a++) {
                                            for (var b = 0; b < tempItems[a].BadTypes.length; b++) {
                                                if (allBadNames[i] === tempItems[a].BadTypes[b].BadTypeName) {
                                                    numBadName+=tempItems[a].BadTypes[b].Num;   
                                                }
                                            }
                                        }
                                        if (numBadName != 0) {
                                            itemallBadNames.push({
                                                Num: numBadName,
                                                BadTypeName: allBadNames[i]
                                            });
                                        }
                                    }
                                    res.json({
                                        Data: {
                                          all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                                          other: items,
                                          itemBadTypes:itemallBadNames
                                        },
                                        Error: null
                                    });
                                }else{
                                    res.json({
                                        Data: {
                                          all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                                          other: items,
                                          itemBadTypes:[]
                                        },
                                        Error: null
                                    });
                                }
                            });  
                        } 
                        else{
                            res.json({
                                Data: {
                                  all: {AllNum:allNum,AllQualifiedNum:allQualifiedNum,AllRate:allQualifiedNum/allNum*100},
                                  other: items,
                                  itemBadTypes:[]
                                },
                                Error: null
                            });
                        }  
             

                        // getDayBadTypes(date).then(function(badTypes) {
                        //     res.json({
                        //         Data: {
                        //             all: { AllNum: allNum, AllQualifiedNum: allQualifiedNum, AllRate: allQualifiedNum / allNum * 100 },
                        //             other: items,
                        //             badTypes: badTypes
                        //         },
                        //         Error: null
                        //     });
                        // }, function (err) {
                        //     res.json({
                        //         Data: null,
                        //         Error: err
                        //     });
                        // });
                    }
                });
            }
        }
    });
    
};

function getDayBadTypes(dayTime) {
    var deferred = Q.defer();

    qcRecordController.getDurationBadTypes(
        new Date(dayTime + " 00:00:00"), new Date(dayTime + " 23:59:59")
    ).then(function(records) {
        if (!records || records.length === 0) {
            deferred.resolve([]);
            return;
        }
        extendEnumController.findEnumOptions('BadType', function(err, option) {
            if (err) {
                deferred.reject(err);
                return;
            }
            var results = [];
            _.forEach(records, function(record) {
                results.push({
                    name: option[record.BadType],
                    value: record.count
                });
            });
            deferred.resolve(results);
        });
    }, function(err) {
        deferred.reject(err);

    });
}

//查找品质记录
function queryQCRecord (unbizRecord,unqcRecords) {
    var deferred = Q.defer();

    qcRecordController.findAllQCRecords(unbizRecord, function (err, results) {
        if (err) {
            deferred.reject(err);
        }
        else {
            if (results) {
                for (var i = 0; i < results.length; i++) {
                    unqcRecords.push(results[i]);
                }
            }
            deferred.resolve(unqcRecords);
        }               
    });

    return deferred.promise;
}
//查找每个型号的品质记录，然后取每个型号的不良类型数组
function queryEachQCRecord(item, badTypeOptions){
    var deferred = Q.defer();
    var promiseQCRecords = [];
    var unqcRecords = [];//存入每个型号所有品质记录       
    item.nobizRecords.forEach(function (nobizRecord) {
        promiseQCRecords.push(queryQCRecord(nobizRecord, unqcRecords));   
    });
    
    Q.all(promiseQCRecords).then(function () {
        //获取每个型号不良类型数组
        if(unqcRecords.length>0){
            item.BadTypes = queryEachCodeBadTypes(unqcRecords, badTypeOptions);   
        }
        else{
            item.BadTypes = [];
        }
        deferred.resolve(item);
        
    });
    return deferred.promise;
}

function queryEachCodeBadTypes(unqcRecords, badTypeOptions){
    //找到不同的BadType
    var BadTypes = [unqcRecords[0].BadType];
    for (var i = 0; i < unqcRecords.length; i++) {
        var repeat = false;
        for (var j = 0; j < BadTypes.length; j++) {
            if (unqcRecords[i].BadType === BadTypes[j]) {
                repeat = true;
                break;
            }
        }
        if (!repeat) {
            BadTypes.push(unqcRecords[i].BadType);
        }
    }

    //按BadType分组
    var itemBadTypes = [];
    for (var i = 0; i < BadTypes.length; i++) {   
        var numBadType = 0;//统计每BadType的总数  
        for (var a = 0; a < unqcRecords.length; a++) {
            var tempBadType = unqcRecords[a].BadType;
            if (BadTypes[i] === tempBadType) {
                numBadType++;   
            }
        }
        if (numBadType != 0) {
            itemBadTypes.push({
                BadType: BadTypes[i],
                Num: numBadType,
                BadTypeName: ''
            });
        }
    }
    itemBadTypes.forEach(function (itemBadType) {
        for (var i = 0; i < badTypeOptions.length; i++) {
            if (badTypeOptions[i].Value === itemBadType.BadType) {
                itemBadType.BadTypeName = badTypeOptions[i].Name;           
            }
        }   
    });

    return itemBadTypes;
}

